#include <iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head || k == 1)return head;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* prev = dummy;
        while (true) {
            ListNode* check = prev;
            for (int i = 0; i < k; i++) {
                check = check->next;
                if (!check)return dummy->next;
            }
            ListNode* first = prev ->next;
            ListNode* curr = first;
            ListNode* last = nullptr;
            for (int j = 0; j < k; j++) {
                ListNode* next = curr->next;
                curr->next = last;
                last = curr;
                curr = next;
            }
            prev->next = last;
            first->next = curr;
            prev = first;
        }
        return dummy->next;
    }
};